package com.mdd.admin.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.service.system.ICouponReceiveService;
import com.mdd.admin.validate.common.PageParam;
import com.mdd.admin.validate.system.CouponReceiveParam;
import com.mdd.admin.vo.system.CouponReceiveListVo;
import com.mdd.admin.vo.system.CouponReceiveDetailVo;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.course.Course;
import com.mdd.common.entity.system.CouponReceive;
import com.mdd.common.mapper.system.CouponReceiveMapper;
import com.mdd.common.utils.ArrayUtil;
import com.mdd.common.utils.StringUtil;
import com.mdd.common.utils.TimeUtil;
import com.mdd.common.utils.UrlUtil;
import com.mdd.common.config.GlobalConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.util.*;

/**
 * 领取记录实现类
 * @author panweiliang
 */
@Service
public class CouponReceiveServiceImpl implements ICouponReceiveService {
        
    @Resource
    CouponReceiveMapper couponReceiveMapper;

    /**
     * 领取记录列表
     *
     * @author panweiliang
     * @param pageParam 分页参数
     * @param params 搜索参数
     * @return PageResult<CouponReceiveListVo>
     */
    @Override
    public PageResult<CouponReceiveListVo> list(PageParam pageParam, Map<String, String> params) {
        Integer page  = pageParam.getPageNo();
        Integer limit = pageParam.getPageSize();

        MPJQueryWrapper<CouponReceive> mpjQueryWrapper = new MPJQueryWrapper<CouponReceive>()
                .selectAll(CouponReceive.class)
                .select("user.nickname, user.avatar, coupon.title AS couponTitle, coupon.receiving_method AS receivingMethod ")
                .innerJoin("?_user user ON user.id = t.user_id".replace("?_", GlobalConfig.knowledgePaymentTablePrefixe))
                .innerJoin("?_coupon coupon ON coupon.id = t.coupon_id".replace("?_", GlobalConfig.knowledgePaymentTablePrefixe))
                        .orderByDesc("t.receive_time");


        couponReceiveMapper.setSearch(mpjQueryWrapper, params, new String[]{
                "like:couponTitle@coupon.title:str",
                "like:issuer@t.issuer:str",
                "=:receivingMethod@coupon.receiving_method:int",
                "datetime:startTime-endTime@t.receive_time:str",
        });

        if (StringUtil.isNotEmpty(params.get("status"))) {
            String status = params.get("status");
            mpjQueryWrapper.eq("t.status", status);
        }

        if (StringUtil.isNotEmpty(params.get("keyword"))) {
            String keyword = params.get("keyword");
            mpjQueryWrapper.nested(wq->wq
                    .like("user.sn", keyword).or()
                    .like("user.nickname", keyword).or()
                    .like("user.mobile", keyword));
        }

        IPage<CouponReceiveListVo> iPage = couponReceiveMapper.selectJoinPage(new Page<>(page, limit), CouponReceiveListVo.class, mpjQueryWrapper);

        for(CouponReceiveListVo item : iPage.getRecords()) {
            item.setAvatar(UrlUtil.toAbsoluteUrl(item.getAvatar()));
            item.setExpireTime(TimeUtil.timestampToDate(item.getExpireTime()));
            item.setReceiveTime(TimeUtil.timestampToDate(item.getReceiveTime()));
            item.setUsedTime(TimeUtil.timestampToDate(item.getUsedTime()));
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
    }

    /**
     * 作废领取记录
     *
     * @author panweiliang
     * @param id 主键ID
     */
    @Override
    @Transactional
    public void cancel(String id) {
        if (StringUtil.isNotEmpty(id)) {
            String[] ids = id.split(",");
            for(int i = 0; i < ids.length; i++) {
                CouponReceive model = couponReceiveMapper.selectOne(
                        new QueryWrapper<CouponReceive>()
                                .eq("id", ids[i])
                                .last("limit 1"));
                Assert.notNull(model, "数据不存在!");
                Assert.isTrue(model.getStatus().intValue() != 1, "存在已使用的优惠券，不能批量作废");
                model.setStatus(2);
//                model.setExpireTime(TimeUtil.timestamp());
                this.couponReceiveMapper.updateById(model);
            }
        }
    }

    @Override
    public Map<String, Object> count() {
        Map<String, Object> count = new HashMap<>();
        count.put("all_num", couponReceiveMapper.countAll());
        count.put("used_num", couponReceiveMapper.countByStatus(1));
        count.put("not_used_num", couponReceiveMapper.countByStatus(0));
        count.put("closed_num", couponReceiveMapper.countByStatus(2));
        count.put("expired_num", couponReceiveMapper.countByStatus(-1));
        return count;
    }

    @Override
    public Long countUsedByUserId(Integer userId) {
        return couponReceiveMapper.countUsedByUserId(userId);
    }

    @Override
    public List<CouponReceive> getByStatus(Integer status) {
        return couponReceiveMapper.getByStatus(status);
    }

    @Override
    public void expire(Long curTime) {
        this.couponReceiveMapper.expire(curTime);
    }
}
